import React, { useState, useMemo } from 'react';

// 假设你的公司Logo图片路径
// 如果Logo在public文件夹下，可以直接写 '/company-logo.png'
import CompanyLogo from '../../public/logo.png'; 

// 定义数据类型接口
interface CarData {
  status: string;
  vin: string;
  rmbUnitPrice: number;
  usdUnitPrice: number;
  taxRMB: number;
  totalPriceWithTaxRMB: number;
  otherFeesRMB: number;
  totalCostRMB: number;
  mileage: number;
  conditionPaint: string;
  carConfiguration: string;
  purchaseMode: string;
  inspectionReport: string;
  productName: string;
  customsDeclarationName: string;
  seatingCapacity: number;
  exterior: string;
  interior: string;
  driveSystem: string;
  oceanBillOfLadingNo: string;
  client: string;
}

const DataTableAbroad: React.FC = () => {
  // 示例数据，你可以根据需要添加更多或从 API 获取
  const [data] = useState<CarData[]>([
    {
      status: '已销售',
      vin: 'VIN1234567890ABCDE',
      rmbUnitPrice: 250000,
      usdUnitPrice: 35000,
      taxRMB: 32500,
      totalPriceWithTaxRMB: 282500,
      otherFeesRMB: 5000,
      totalCostRMB: 287500,
      mileage: 15000,
      conditionPaint: '优秀/原厂漆，无划痕',
      carConfiguration: '豪华版，带全景天窗和自动驾驶',
      purchaseMode: '现车',
      inspectionReport: '合格',
      productName: '特斯拉 Model 3',
      customsDeclarationName: '纯电动乘用车',
      seatingCapacity: 5,
      exterior: '白色',
      interior: '黑色皮质',
      driveSystem: '全轮驱动',
      oceanBillOfLadingNo: 'BL123456789',
      client: '张三',
    },
    {
      status: '在库',
      vin: 'VIN9876543210FEDCB',
      rmbUnitPrice: 300000,
      usdUnitPrice: 42000,
      taxRMB: 39000,
      totalPriceWithTaxRMB: 339000,
      otherFeesRMB: 6000,
      totalCostRMB: 345000,
      mileage: 5000,
      conditionPaint: '良好/左前门小刮擦',
      carConfiguration: '标准续航，无额外选配',
      purchaseMode: '期货',
      inspectionReport: '合格',
      productName: '蔚来 ES6',
      customsDeclarationName: '纯电动乘用车',
      seatingCapacity: 5,
      exterior: '蓝色',
      interior: '米色织物',
      driveSystem: '前轮驱动',
      oceanBillOfLadingNo: 'BL987654321',
      client: '李四',
    },
    {
      status: '运输中',
      vin: 'VIN5432167890ABCDEF',
      rmbUnitPrice: 450000,
      usdUnitPrice: 63000,
      taxRMB: 58500,
      totalPriceWithTaxRMB: 508500,
      otherFeesRMB: 8000,
      totalCostRMB: 516500,
      mileage: 100,
      conditionPaint: '全新/无瑕疵',
      carConfiguration: '高性能版，带矩阵大灯',
      purchaseMode: '现车',
      inspectionReport: '合格',
      productName: '保时捷 Taycan',
      customsDeclarationName: '纯电动跑车',
      seatingCapacity: 4,
      exterior: '黑色',
      interior: '红色真皮',
      driveSystem: '全轮驱动',
      oceanBillOfLadingNo: 'BL456789123',
      client: '王五',
    },
    {
      status: '待出口', 
      vin: 'VIN1122334455667788',
      rmbUnitPrice: 180000,
      usdUnitPrice: 25000,
      taxRMB: 23400,
      totalPriceWithTaxRMB: 203400,
      otherFeesRMB: 3000,
      totalCostRMB: 206400,
      mileage: 30000,
      conditionPaint: '一般/多处小划痕',
      carConfiguration: '舒适版',
      purchaseMode: '寄售',
      inspectionReport: '有缺陷',
      productName: '大众 朗逸',
      customsDeclarationName: '轿车',
      seatingCapacity: 5,
      exterior: '银色',
      interior: '灰色织物',
      driveSystem: '前轮驱动',
      oceanBillOfLadingNo: 'BL555666777',
      client: '赵六',
    },
    {
      status: '已出口', 
      vin: 'VIN9988776655443322',
      rmbUnitPrice: 600000,
      usdUnitPrice: 85000,
      taxRMB: 78000,
      totalPriceWithTaxRMB: 678000,
      otherFeesRMB: 10000,
      totalCostRMB: 688000,
      mileage: 1000,
      conditionPaint: '全新/无瑕疵',
      carConfiguration: '顶配版',
      purchaseMode: '现车',
      inspectionReport: '合格',
      productName: '奔驰 S级',
      customsDeclarationName: '豪华轿车',
      seatingCapacity: 4,
      exterior: '黑色',
      interior: '棕色真皮',
      driveSystem: '后轮驱动',
      oceanBillOfLadingNo: 'BL111222333',
      client: '钱七',
    },
    // 添加更多数据以测试滚动效果和状态统计
    {
      status: '已销售',
      vin: 'VIN1234567890ABCDE',
      rmbUnitPrice: 250000,
      usdUnitPrice: 35000,
      taxRMB: 32500,
      totalPriceWithTaxRMB: 282500,
      otherFeesRMB: 5000,
      totalCostRMB: 287500,
      mileage: 15000,
      conditionPaint: '优秀/原厂漆，无划痕',
      carConfiguration: '豪华版，带全景天窗和自动驾驶',
      purchaseMode: '现车',
      inspectionReport: '合格',
      productName: '特斯拉 Model 3',
      customsDeclarationName: '纯电动乘用车',
      seatingCapacity: 5,
      exterior: '白色',
      interior: '黑色皮质',
      driveSystem: '全轮驱动',
      oceanBillOfLadingNo: 'BL123456789',
      client: '张三',
    },
    {
      status: '在库',
      vin: 'VIN9876543210FEDCB',
      rmbUnitPrice: 300000,
      usdUnitPrice: 42000,
      taxRMB: 39000,
      totalPriceWithTaxRMB: 339000,
      otherFeesRMB: 6000,
      totalCostRMB: 345000,
      mileage: 5000,
      conditionPaint: '良好/左前门小刮擦',
      carConfiguration: '标准续航，无额外选配',
      purchaseMode: '期货',
      inspectionReport: '合格',
      productName: '蔚来 ES6',
      customsDeclarationName: '纯电动乘用车',
      seatingCapacity: 5,
      exterior: '蓝色',
      interior: '米色织物',
      driveSystem: '前轮驱动',
      oceanBillOfLadingNo: 'BL987654321',
      client: '李四',
    },
    {
      status: '运输中',
      vin: 'VIN5432167890ABCDEF',
      rmbUnitPrice: 450000,
      usdUnitPrice: 63000,
      taxRMB: 58500,
      totalPriceWithTaxRMB: 508500,
      otherFeesRMB: 8000,
      totalCostRMB: 516500,
      mileage: 100,
      conditionPaint: '全新/无瑕疵',
      carConfiguration: '高性能版，带矩阵大灯',
      purchaseMode: '现车',
      inspectionReport: '合格',
      productName: '保时捷 Taycan',
      customsDeclarationName: '纯电动跑车',
      seatingCapacity: 4,
      exterior: '黑色',
      interior: '红色真皮',
      driveSystem: '全轮驱动',
      oceanBillOfLadingNo: 'BL456789123',
      client: '王五',
    },
    {
      status: '待出口',
      vin: 'VIN1122334455667788',
      rmbUnitPrice: 180000,
      usdUnitPrice: 25000,
      taxRMB: 23400,
      totalPriceWithTaxRMB: 203400,
      otherFeesRMB: 3000,
      totalCostRMB: 206400,
      mileage: 30000,
      conditionPaint: '一般/多处小划痕',
      carConfiguration: '舒适版',
      purchaseMode: '寄售',
      inspectionReport: '有缺陷',
      productName: '大众 朗逸',
      customsDeclarationName: '轿车',
      seatingCapacity: 5,
      exterior: '银色',
      interior: '灰色织物',
      driveSystem: '前轮驱动',
      oceanBillOfLadingNo: 'BL555666777',
      client: '赵六',
    },
    {
      status: '已出口',
      vin: 'VIN9988776655443322',
      rmbUnitPrice: 600000,
      usdUnitPrice: 85000,
      taxRMB: 78000,
      totalPriceWithTaxRMB: 678000,
      otherFeesRMB: 10000,
      totalCostRMB: 688000,
      mileage: 1000,
      conditionPaint: '全新/无瑕疵',
      carConfiguration: '顶配版',
      purchaseMode: '现车',
      inspectionReport: '合格',
      productName: '奔驰 S级',
      customsDeclarationName: '豪华轿车',
      seatingCapacity: 4,
      exterior: '黑色',
      interior: '棕色真皮',
      driveSystem: '后轮驱动',
      oceanBillOfLadingNo: 'BL111222333',
      client: '钱七',
    },
  ]);

  const [selectedRowIndex, setSelectedRowIndex] = useState<number | null>(null);

  // 定义表头（显示给用户的中文名称）
  // 调整 headers 和 dataKeys 的顺序以匹配新的固定列结构
  const headers = [
    "序号", // 固定在最左边
    "状态", // 固定在序号后面
    "车架号(VIN)", "单价(RMB)", "单价(USD)", "税额", "价税合计",
    "其他费用", "总成本", "公里数", "车况车漆", "选车配置", "采购模式", "检测报告",
    "商品名称", "报关名称", "座位数", "外观", "内饰", "驱动系统", "海运提单号", "客户"
  ];

  // 定义数据对应的键名（用于从 CarData 对象中取值和 CSV 导出）
  // 注意：CSV 导出时，"序号"不是数据的一部分，所以dataKeys不需要包含它
  const dataKeys: (keyof CarData)[] = [
    "status", "vin", "rmbUnitPrice", "usdUnitPrice", "taxRMB", "totalPriceWithTaxRMB",
    "otherFeesRMB", "totalCostRMB", "mileage", "conditionPaint", "carConfiguration", "purchaseMode", "inspectionReport",
    "productName", "customsDeclarationName", "seatingCapacity", "exterior", "interior", "driveSystem", "oceanBillOfLadingNo", "client"
  ];

  // 定义状态对应的文字颜色映射
  const statusTextColors: { [key: string]: string } = {
    '已销售': 'text-green-600', 
    '在库': 'text-blue-600', 
    '运输中': 'text-yellow-600', 
    '待出口': 'text-purple-600', 
    '已出口': 'text-indigo-600', 
    // 可以添加更多状态和对应的颜色
  };

  // 使用 useMemo 缓存统计结果，避免不必要地重新计算
  const statusCounts = useMemo(() => {
    const counts: { [key: string]: number } = {};
    data.forEach(item => {
      counts[item.status] = (counts[item.status] || 0) + 1;
    });
    return counts;
  }, [data]); // 只有当 data 变化时才重新计算

  // 处理数据下载为 CSV 文件
  const handleDownload = () => {
    const csvRows = [];
    // CSV表头需要包含序号，且状态列不需要在dataKeys中动态处理颜色
    csvRows.push(["序号", ...headers.slice(1)].join(',')); 

    for (let i = 0; i < data.length; i++) {
      const row = data[i];
      const values = [i + 1, ...dataKeys.map(key => { 
        let value = row[key];
        if (typeof value === 'number') {
            if (key.includes('Price') || key.includes('Cost') || key.includes('Fees') || key.includes('Tax')) {
                value = value.toFixed(2);
            } else {
                value = value.toString();
            }
        }
        if (typeof value === 'string' && (value.includes(',') || value.includes('"') || value.includes('\n'))) {
          return `"${value.replace(/"/g, '""')}"`;
        }
        return value;
      })];
      csvRows.push(values.join(','));
    }

    const csvString = csvRows.join('\n');
    const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '车辆数据.csv'); 
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url); 
  };

  // 处理行点击事件
  const handleRowClick = (index: number) => {
    setSelectedRowIndex(index === selectedRowIndex ? null : index); 
  };

  return (
    <div className="min-h-screen bg-gray-100 p-4 md:p-8"> 
      {/* 公司名称和Logo区域 */}
      <div className="flex flex-col md:flex-row items-center justify-between bg-white shadow-md rounded-lg p-4 md:p-6 mb-4 md:mb-8">
        <div className="flex items-center mb-4 md:mb-0">
          <img 
            src={CompanyLogo} 
            alt="公司Logo" 
            className="h-12 w-12 md:h-16 md:w-16 mr-2 md:mr-4 object-contain" 
          />
          <h1 className="text-xl md:text-3xl font-bold text-gray-800 text-center md:text-left">
            杰尔汽车出口数据
          </h1>
        </div>
        <button
          onClick={handleDownload}
          className="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 md:px-6 rounded-lg shadow-lg transition duration-300 ease-in-out w-full md:w-auto"
        >
          下载数据 (CSV)
        </button>
      </div>

      {/* 数据表格区域 - 添加了高度限制和滚动条 */}
      <div className="bg-white shadow-md rounded-lg overflow-hidden">
        {/* max-h-[calc(100vh-250px)] 示例：假设顶部内容和底部统计高250px */}
        <div className="overflow-auto max-h-[calc(100vh-250px)] lg:max-h-[calc(100vh-300px)]"> 
          <table className="min-w-full divide-y divide-gray-200 border-collapse"> 
            <thead className="bg-gray-50">
              <tr>
                {headers.map((header, index) => (
                  <th
                    key={index}
                    scope="col"
                    className={`
                      px-4 py-2 md:px-6 md:py-3 text-left text-xs md:text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap
                      sticky top-0 border border-gray-200
                      ${index === 0 ? 'left-0 z-30 bg-gray-100' : ''} /* 序号列 */
                      ${index === 1 ? 'left-[calc(3rem+2px)] z-20 bg-gray-50' : ''} /* 状态列, 3rem是序号列宽度, 2px是边框 */
                      ${index > 1 ? 'z-20 bg-gray-50' : ''} /* 其他列 */
                    `}
                  >
                    {header}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {data.map((row, rowIndex) => (
                <tr 
                  key={rowIndex} 
                  onClick={() => handleRowClick(rowIndex)} 
                  className={`
                    cursor-pointer transition-colors duration-200 ease-in-out
                    ${selectedRowIndex === rowIndex ? 'bg-blue-50/50 hover:bg-blue-100' : 'hover:bg-gray-50'}
                  `}
                >
                  {/* 序号列：固定在左侧最前面 */}
                  <td 
                    className={`
                      px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm font-medium text-gray-900 sticky left-0 z-10 border border-gray-200 text-center
                      ${selectedRowIndex === rowIndex ? 'bg-blue-100' : 'bg-white'} 
                    `}
                  >
                    {rowIndex + 1}
                  </td>
                  {/* 状态列：固定在序号列后面，文字颜色，无背景色 */}
                  <td 
                    className={`
                      px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200
                      sticky left-[calc(3rem+2px)] /* 3rem是序号列宽度, 2px是边框 */
                      z-10 /* 和序号列 z-index 保持一致即可 */
                      ${selectedRowIndex === rowIndex ? 'bg-blue-100' : 'bg-white'} /* 选中时背景色 */
                      ${statusTextColors[row.status] || ''} 
                    `}
                  >
                    {row.status}
                  </td>
                  {/* 其他单元格 */}
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.vin}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    ¥{row.rmbUnitPrice.toLocaleString()}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    ${row.usdUnitPrice.toLocaleString()}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    ¥{row.taxRMB.toLocaleString()}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    ¥{row.totalPriceWithTaxRMB.toLocaleString()}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    ¥{row.otherFeesRMB.toLocaleString()}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    ¥{row.totalCostRMB.toLocaleString()}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.mileage.toLocaleString()} 公里
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.conditionPaint}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.carConfiguration}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.purchaseMode}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.inspectionReport}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.productName}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.customsDeclarationName}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.seatingCapacity}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.exterior}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.interior}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.driveSystem}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.oceanBillOfLadingNo}
                  </td>
                  <td className="px-4 py-3 md:px-6 md:py-4 whitespace-nowrap text-xs md:text-sm text-gray-500 border border-gray-200">
                    {row.client}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 底部数据统计区域 */}
      <div className="bg-white shadow-md rounded-lg p-4 md:p-6 mt-4 md:mt-8 text-gray-700 text-sm md:text-base">
        <h2 className="text-lg md:text-xl font-bold mb-2">数据统计</h2>
        <p className="mb-1">
          总数据条数: <span className="font-semibold text-blue-600">{data.length}</span> 条
        </p>
        <div className="flex flex-wrap gap-x-6 gap-y-2">
          {Object.entries(statusCounts).map(([status, count]) => (
            <p key={status} className="mr-4">
              <span className={`font-semibold ${statusTextColors[status] || 'text-gray-800'} px-0.5 rounded-md`}>
                {status}
              </span>
              : <span className="font-semibold text-gray-800">{count}</span> 条
            </p>
          ))}
        </div>
      </div>
    </div>
  );
};

export default DataTableAbroad;